package com.hk.service.quartz;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.hk.commons.entity.yingmi.YingmiOrderFile;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.service.yingmi.IYingmiOrderFile;


public class YingmiOrderFileQuartz extends BaseQuartz {

	private Logger logger = LoggerFactory
			.getLogger(YingmiOrderFileQuartz.class);

	@Autowired
	private YingmiApiUtils utils;

	@Autowired
	private IYingmiOrderFile orderFielService;

	@Value("${yingmi.file.host}")
	private String host;

	@Value("${yingmi.data.file}")
	private String fileSave;

	@Override
	public void start() {
		/**
		 * /file/yingmi_<商户号>_order_<YYYYMMDD>.txt
		 */
		SimpleDateFormat sf = new SimpleDateFormat("YYYMMdd");
		String date = sf.format(System.currentTimeMillis());
		String path = "yingmi_" + "1017" + "_order_" + date;
		Map<String, String> params = new HashMap<>();
		String fileName = path + ".txt";
		String fileStr = utils.fileGet("/file/" + fileName, params, host);

		// 生成订单流文件
		Path filePath = Paths.get(fileSave + fileName);
		if (!Files.exists(Paths.get(fileSave + fileName))) {
			try {
				Files.write(filePath, fileStr.getBytes("UTF-8"));
				ExecutorService executor = Executors.newFixedThreadPool(1);
		        Runnable task = new Runnable() {
		            public void run() {
		            	saveOrderDate(fileName);
		            }
		        };
		        executor.execute(task);
		        executor.shutdown();
			} catch (IOException e) {
				logger.error("file:{} error:{}", fileName, e);
			}
		}
	}

	private void saveOrderDate(String fileName) {
		List<String> list = new ArrayList<>();
		try {
			 list = Files.lines(Paths.get(fileSave + fileName)).collect(Collectors.toList());
			 String[] ss = null;
			 for (int i = 2; i < list.size(); i++) {
				 YingmiOrderFile yof = new YingmiOrderFile();
				 ss = StringUtils.splitPreserveAllTokens(list.get(i), '|');
//				 yof.setId((int)nums + 1);
				 yof.setBrokerUserId(ss[1]);
				 yof.setAccountId(ss[2]);
				 yof.setBrokerOrderNo(ss[3]);
				 yof.setOrderId(ss[4]);
				 yof.setPaymentMethodId(ss[5]);
				 yof.setFundCode(ss[6]);
				 yof.setShareType(ss[7]);
				 yof.setFundOrderCode(ss[8]);
				 yof.setChangeFundCode(StringUtils.isEmpty(ss[9]) ? "" : ss[9]);
				 yof.setChangeShareType(StringUtils.isEmpty(ss[10]) ? "" : ss[10]);
				 yof.setAppliedAmount(StringUtils.isEmpty(ss[11]) ?  new BigDecimal(0) : new BigDecimal(ss[11]));
				 yof.setConfirmShare(StringUtils.isEmpty(ss[12]) ? new BigDecimal(0) : new BigDecimal(ss[12]));
				 yof.setAppliedDiscount(StringUtils.isEmpty(ss[13]) ? new BigDecimal(0) : new BigDecimal(ss[13]));
				 yof.setPayStatus(StringUtils.isEmpty(ss[14]) ?  0 : Integer.valueOf(ss[14]));
				 yof.setOrderStatus(StringUtils.isEmpty(ss[15]) ?  0 : Integer.valueOf(ss[15]));
				 yof.setOrderDetail(StringUtils.isEmpty(ss[16]) ? "" : ss[16]);
				 yof.setRemarks(StringUtils.isEmpty(ss[17]) ? "" : ss[17]);
				 
				 orderFielService.add(yof);
			 }
		} catch (Exception e) {
			logger.error("fileName :{} saveOrderDate fail", fileName);
			e.printStackTrace();
		}

	}

}
